﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace Ledict.ConditionExtract.Controls
{
    public partial class colFileter : UserControl
    {
        public string _ccName;
        public string CCName
        {
            get { return _ccName; }
            set
            {
                _ccName = value;
                if (!string.IsNullOrEmpty(_ccName))
                {
                    if (_ccName == "刑事")
                    {
                        colCombConfigType.SelectedItem = "情形情节";
                        colCombConfigType.Enabled = false;
                    }
                    else if (_ccName == "民事")
                    {
                        colCombConfigType.SelectedItem = "要素";
                        colCombConfigType.Enabled = false;

                    }
                    else if (_ccName == "程序法")
                    {
                        colCombConfigType.SelectedItem = "字段";
                        colCombConfigType.Enabled = false;

                    }
                }
            }
        }
        public colFileter()
        {
            InitializeComponent();
            
            //colPanelFileter.VerticalScroll.Visible = true; 
        }

        private XmlDocument m_fileterXML = new XmlDocument();
        private List<colColumnFileter> m_columnFileterList = new List<colColumnFileter>();

        private LinkLabel m_addbtn = null;

        private void colCombConfigType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (colCombConfigType.SelectedIndex)
            {
                case 0:
                    CreateColumnFileter();
                    break;
                case 1:
                    CreateColumnFileterCase();
                    break;
                case 2:
                    CreateColumnFileterElement();
                    break;
            }
            //if(colCombConfigType.SelectedIndex == 0)
        }

        private void CreateColumnFileterElement(element el = null)
        {
            colColumnFileter cf = new colColumnFileter(this.Font, el);
            cf.Left = 0;
            cf.Top = m_columnFileterList.Count * (30 + 2);
            cf.Width = 530;
            cf.Height = 30;
            cf.DeleteBtnClicked += new colColumnFileter.DeleteButtonClick(colColumnFileter_deleteButtonClick);
            colPanelFileter.Controls.Add(cf);
            m_columnFileterList.Add(cf);

            if (m_addbtn == null)
            {
                m_addbtn = new LinkLabel();
                m_addbtn.Text = "添加";
                Graphics graphics = CreateGraphics();
                SizeF sizeF = graphics.MeasureString(m_addbtn.Text, this.Font);
                m_addbtn.Width = (int)(Math.Ceiling(sizeF.Width)) + 1;
                m_addbtn.Height = (int)(Math.Ceiling(sizeF.Height));
                m_addbtn.Left = 0;
                m_addbtn.LinkClicked += new LinkLabelLinkClickedEventHandler(this.colLinkButton_Click);
                colPanelFileter.Controls.Add(m_addbtn);
            }
            m_addbtn.Top = m_columnFileterList.Count * (30 + 2);
        }

        private void CreateColumnFileterCase(cause ca = null)
        {
            colColumnFileter cf = new colColumnFileter(this.Font, ca);
            cf.Left = 0;
            cf.Top = m_columnFileterList.Count * (30 + 2);
            cf.Width = 530;
            cf.Height = 30;
            cf.DeleteBtnClicked += new colColumnFileter.DeleteButtonClick(colColumnFileter_deleteButtonClick);
            colPanelFileter.Controls.Add(cf);
            m_columnFileterList.Add(cf);

            if (m_addbtn == null)
            {
                m_addbtn = new LinkLabel();
                m_addbtn.Text = "添加";
                Graphics graphics = CreateGraphics();
                SizeF sizeF = graphics.MeasureString(m_addbtn.Text, this.Font);
                m_addbtn.Width = (int)(Math.Ceiling(sizeF.Width)) + 1;
                m_addbtn.Height = (int)(Math.Ceiling(sizeF.Height));
                m_addbtn.Left = 0;
                m_addbtn.LinkClicked += new LinkLabelLinkClickedEventHandler(this.colLinkButton_Click);
                colPanelFileter.Controls.Add(m_addbtn);
            }
            m_addbtn.Top = m_columnFileterList.Count * (30 + 2);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xml"></param>
        public void SetFileter(string xml)
        {
            try
            {
                m_fileterXML.LoadXml(xml);

                string type = m_fileterXML.SelectSingleNode("/Fileter/type").InnerText;
                colCombConfigType.SelectedItem = type;
                Clear();
                if (type == "字段")
                {
                    XmlNodeList nodelist = m_fileterXML.SelectNodes("/Fileter/table");
                    foreach (XmlNode Node in nodelist)
                    {
                        XmlNodeList childNodeList = Node.ChildNodes;
                        table tb = new table();
                        foreach (XmlNode childNode in childNodeList)
                        {
                            switch (childNode.Name)
                            {
                                case "name":
                                    tb.name = childNode.InnerText;
                                    break;
                                case "field":
                                    tb.field = childNode.InnerText;
                                    break;
                                case "value":
                                    tb.value = childNode.InnerText;
                                    break;
                            }
                        }
                        CreateColumnFileter(tb);
                    }
                    //int a = 0;
                }
                else if (type == "情形情节")
                {
                    XmlNodeList nodelist = m_fileterXML.SelectNodes("/Fileter/cause");
                    foreach (XmlNode Node in nodelist)
                    {
                        XmlNodeList childNodeList = Node.ChildNodes;
                        cause ca = new cause();
                        foreach (XmlNode childNode in childNodeList)
                        {
                            switch (childNode.Name)
                            {
                                case "id":
                                    ca.id = childNode.InnerText;
                                    break;
                            }
                        }
                        CreateColumnFileterCase(ca);
                    }

                }
                else if (type == "要素")
                {
                    XmlNodeList nodelist = m_fileterXML.SelectNodes("/Fileter/element");
                    foreach (XmlNode Node in nodelist)
                    {
                        XmlNodeList childNodeList = Node.ChildNodes;
                        element el = new element();
                        foreach (XmlNode childNode in childNodeList)
                        {
                            switch (childNode.Name)
                            {
                                case "xpath":
                                    el.xpath = childNode.InnerText;
                                    break;
                                case "value":
                                    el.value = childNode.InnerText;
                                    break;
                            }
                        }
                        CreateColumnFileterElement(el);
                    }
                }
                //m_columnFileterList.RemoveAt(i);
                //   colPanelFileter.Controls.Remove(cf);
                //string a = colCombConfigType.SelectedItem.ToString();
            }
            catch
            {
                Clear();
            }
            //foreach (XmlNode Node in nodelist)
            //{
            //    //if(Node.Name == "type")
            //    //RuleObject rule = new RuleObject(Node, m_caseId);
            //    //string xPath = "";
            //    //string ret = rule.GetRet(ref xPath);
            //    //retDict.Add(xPath, ret);
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetFileter()
        {
            Fileter fileter = new Fileter();
            if (colCombConfigType.SelectedItem != null)
            {
                fileter.type = colCombConfigType.SelectedItem.ToString();
                if (fileter.type == "字段")
                {
                    foreach (colColumnFileter cf in m_columnFileterList)
                    {
                        if (fileter.tablelist == null)
                        {
                            fileter.tablelist = new List<table>();
                        }
                        if (cf.Get() == null)
                        {
                            fileter.tablelist.Clear();
                            return "";
                        }
                        fileter.tablelist.Add(cf.Get());
                    }
                }
                else if (fileter.type == "情形情节")
                {
                    foreach (colColumnFileter cf in m_columnFileterList)
                    {
                        if (fileter.causelist == null)
                        {
                            fileter.causelist = new List<cause>();
                        }
                        if (cf.causeGet() == null)
                        {
                            fileter.causelist.Clear();
                            return "";
                        }
                        fileter.causelist.Add(cf.causeGet());
                    }
                }
                else if (fileter.type == "要素")
                {
                    foreach (colColumnFileter cf in m_columnFileterList)
                    {
                        if (fileter.elementlist == null)
                        {
                            fileter.elementlist = new List<element>();
                        }
                        if (cf.elementGet() == null)
                        {
                            fileter.elementlist.Clear();
                            return "";
                        }
                        fileter.elementlist.Add(cf.elementGet());
                    }
                }

                string xml = Serializer(typeof(Fileter), fileter);
                if (xml != "")
                {
                    m_fileterXML.LoadXml(xml);
                    return m_fileterXML.OuterXml;
                }
            }
            return "";
        }

        public static string Serializer(Type type, object obj)
        {
            //创建IO
            MemoryStream Stream = new MemoryStream();
            //设置xml
            XmlWriterSettings settings = new XmlWriterSettings();
            // Remove the <?xml version="1.0" encoding="utf-8"?> 
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;
            //注意如果不设置encoding默认将输出utf-16
            //注意这儿不能直接用Encoding.UTF8如果用Encoding.UTF8将在输出文本的最前面添加4个字节的非xml内容
            settings.Encoding = new UTF8Encoding(false);
            //设置换行符
            settings.NewLineChars = Environment.NewLine;
            XmlWriter writer = XmlWriter.Create(Stream, settings);
            //创建命名空间         
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象
                xml.Serialize(writer, obj, ns);
            }
            catch (InvalidOperationException)
            {
                return "";
            }
            string str = Encoding.UTF8.GetString(Stream.ToArray());
            Stream.Dispose();

            return str;
        }
        /// <summary>
        /// 
        /// </summary>
        private void CreateColumnFileter(table tb = null)
        {
            colColumnFileter cf = new colColumnFileter(this.Font, tb);
            cf.Left = 0;
            cf.Top = m_columnFileterList.Count * (30 + 2);
            cf.Width = 530;
            cf.Height = 30;
            cf.DeleteBtnClicked += new colColumnFileter.DeleteButtonClick(colColumnFileter_deleteButtonClick);
            colPanelFileter.Controls.Add(cf);
            m_columnFileterList.Add(cf);

            if (m_addbtn == null)
            {
                m_addbtn = new LinkLabel();
                m_addbtn.Text = "添加";
                Graphics graphics = CreateGraphics();
                SizeF sizeF = graphics.MeasureString(m_addbtn.Text, this.Font);
                m_addbtn.Width = (int)(Math.Ceiling(sizeF.Width)) + 1;
                m_addbtn.Height = (int)(Math.Ceiling(sizeF.Height));
                m_addbtn.Left = 0;
                m_addbtn.LinkClicked += new LinkLabelLinkClickedEventHandler(this.colLinkButton_Click);
                colPanelFileter.Controls.Add(m_addbtn);
            }
            m_addbtn.Top = m_columnFileterList.Count * (30 + 2);
        }
        /// <summary>
        /// 
        /// </summary>
        private void Refesh()
        {
            for (int i = 0; i < m_columnFileterList.Count; i++)
            {
                colColumnFileter cf = m_columnFileterList[i];
                cf.Top = i * (30 + 2);
            }
            m_addbtn.Top = m_columnFileterList.Count * (30 + 2);
        }
        /// <summary>
        /// 
        /// </summary>
        private void Clear()
        {
            for (int i = 0; i < m_columnFileterList.Count; i++)
            {
                colColumnFileter cf = m_columnFileterList[i];
                colPanelFileter.Controls.Remove(cf);
            }
            m_columnFileterList.Clear();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        private void colColumnFileter_deleteButtonClick(object sender)
        {
            colColumnFileter cf = sender as colColumnFileter;
            for (int i = m_columnFileterList.Count - 1; i >= 0; i--)
            {
                if (cf == m_columnFileterList[i])
                {
                    m_columnFileterList.RemoveAt(i);
                    colPanelFileter.Controls.Remove(cf);
                    break;
                }
            }
            Refesh();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void colLinkButton_Click(object sender, EventArgs e)
        {
            int ctlcount = colPanelFileter.Size.Height / (30 + 2) - 1;
            if (m_columnFileterList.Count <= ctlcount)
            {

                if (_ccName == "刑事")
                {
                    CreateColumnFileterCase();
                }
                else if (_ccName == "民事")
                {
                    CreateColumnFileterElement();
                }
                else if (_ccName == "程序法")
                {
                    CreateColumnFileter();
                }
                   
            }
        }
       
    }
}
